package com.sanqing.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sanqing.dao.base.BaseDao;
import com.sanqing.po.Course;
import com.sanqing.po.Examine;
import com.sanqing.po.ExamineBatch;
import com.sanqing.po.ExamineHis;
import com.sanqing.po.Score;
import com.sanqing.po.Subject;
import com.sanqing.po.User;
import com.sanqing.service.ScoreService;
import com.sanqing.util.Page;
import com.sanqing.util.PageResult;
import com.sanqing.util.PageUtil;
import com.sanqing.util.TimeHelper;

@Service("scoreService")
@Transactional(readOnly = true)
public class ScoreServiceImpl implements ScoreService {

	@Resource(name = "scoreDao")
	private BaseDao<Score, String> scoreDao;

	@Resource(name = "subjectDao")
	private BaseDao<Subject, String> subjectDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Resource(name = "examineHisDao")
	private BaseDao<ExamineHis, String> examineHisDao;

	@Resource(name = "examineDao")
	private BaseDao<Examine, String> examineDao;

	@Override
	public PageResult queryScoreByPage(Page page, Score score, User sysUser) {
		Map<String, Object> map = new HashMap<String, Object>();
		String hql = "from Score a where 1=1";
		if (score.getUser() != null && StringUtils.isNotBlank(score.getUser().getName())) {
			hql += " and a.user.name like:name";
			map.put("name", "%" + score.getUser().getName() + "%");
		}
		if ("1".equals(sysUser.getUserType())) {
			hql += " and a.user.userId=:userId";
			map.put("userId", sysUser.getUserId());
		}
		if(score.getExamineBatch()!=null && StringUtils.isNotBlank(score.getExamineBatch().getName())){
			hql += " and a.examineBatch.name like:batchName";
			map.put("batchName", "%" + score.getExamineBatch().getName() + "%");
		}
		page = PageUtil.createPage(page.getEveryPage(), (int) scoreDao.countHqlResult(hql, map), page.getCurrentPage());// 根据总记录数创建分页信息
		List<Score> list = scoreDao.findByPage(page, hql, map);// 通过分页信息取得试题
		PageResult result = new PageResult(page, list);// 封装分页信息和记录信息，返回给调用处
		return result;
	}

	@Override
	public List<Map<String, Object>> getMyExamList(User sysUser) {
		// String sql = "SELECT a.*,c.score,c.createTime AS examTime, 	CASE WHEN a.courseId IN(SELECT b.courseId  	FROM tb_score b 	WHERE b.userId =?) THEN '已考试' 	ELSE '未考试' END AS state FROM tb_course a LEFT JOIN tb_score c ON a.courseId=c.courseId AND c.userId=? WHERE a.courseId IN( SELECT DISTINCT b.courseId FROM tb_subject b )  ";
		// String sql = "SELECT  m.*,n.state,n.score,n.examTime,n.startTime,n.stopTime FROM    tb_course m    INNER JOIN  (SELECT    a.*,    b.score,   b.createTime AS examTime,   CASE     WHEN a.courseId IN      (SELECT        c.courseId      FROM       tb_score c     WHERE c.userId = ?)      THEN '已考试'      ELSE '未考试'    END AS state  FROM   tb_examine a    LEFT JOIN tb_score b   ON a.courseId=b.courseId   AND b.userId=? WHERE a.grade = ?    AND a.courseId IN    (SELECT DISTINCT      b.courseId    FROM     tb_subject b))n     ON m.courseId=n.courseId";
		String sql = "SELECT    m.*,   n.id, n.examState,   n.score,   n.examedTime,   n.startTime,   n.stopTime  FROM   tb_course m    INNER JOIN  (SELECT       a.*,       b.score,       b.createTime AS examedTime,       CASE         WHEN a.courseId IN          (SELECT            c.courseId          FROM           tb_score c          WHERE c.userId = ?)          THEN '已考试'          ELSE '未考试'        END AS examState  FROM tb_examine a LEFT JOIN tb_score b  ON a.courseId = b.courseId  AND b.userId=? WHERE a.grade = ? AND a.id IN( SELECT  c.examineId FROM tb_questions c))N ON m.courseId = n.courseId ";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, sysUser.getUserId(), sysUser.getUserId(), sysUser.getGrade());
		String crrTime = TimeHelper.getCurrentTime();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				String examineId = (String) list.get(i).get("id");
				Examine examine = examineDao.getByKey(examineId);
				Set<ExamineBatch> examineBatchs = examine.getExamineBatchs();
				for (Iterator<ExamineBatch> iterator = examineBatchs.iterator(); iterator.hasNext();) {
					ExamineBatch batch = iterator.next();
					if (crrTime.compareTo(batch.getStartTime()) < 0) {// 当前时间不开始时间小。考试状态为未开始0
						map.put("startTime", batch.getStartTime());
						map.put("stopTime", batch.getStopTime());
						map.put("examineState", "0");
						break;
					} else if (crrTime.compareTo(batch.getStartTime()) >= 0 && crrTime.compareTo(batch.getStopTime()) < 0) {// 开始正在进行状态1
						map.put("startTime", batch.getStartTime());
						map.put("stopTime", batch.getStopTime());
						map.put("examineState", "1");
						map.put("examineBatchId", batch.getId());
						break;
					} else {

					}
				}

			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Subject> getSubject(String subjectType, String id) {
		Map<String, Object> values = new HashMap<String, Object>();
		values.put("subjectType", subjectType);
		values.put("courseId", id);
		String hql = "from Subject a where a.subjectType=:subjectType and a.course.courseId=:courseId order by rand()";
		Query query = subjectDao.createQuery(hql, values);
		query.setMaxResults(10);// 设置查询记录数
		return query.list();
	}

	@Override
	@Transactional(readOnly = false)
	public void add(Score score) {
		scoreDao.save(score);
	}

	@Override
	public List<Score> getByUserIdAndCourseId(Course course, User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		String hql = "from Score a where 1=1";
		hql += " and a.user=:user";
		hql += " and a.course=:course";
		map.put("course", course);
		map.put("user", user);
		return scoreDao.find(hql, map);
	}

	@Override
	@Transactional(readOnly = false)
	public void accountResult(int result, Course course, User sysUser, List<ExamineHis> examineHis, String examineBatchId) {
		List<Score> scores = getByUserIdAndCourseId(course, sysUser);
		Score score = null;
		if (scores != null && scores.size() > 0) {
			score = scores.get(0);
			score.setScore(result + "");
			score.setCreateTime(TimeHelper.getCurrentTime());
			score.setExamineBatch(new ExamineBatch(examineBatchId));
			jdbcTemplate.update("delete from tb_examine_his  where scoreId=?", new Object[] { score.getId() });
		} else {
			score = new Score();
			score.setCourse(course);
			score.setCreateTime(TimeHelper.getCurrentTime());
			score.setUser(sysUser);
			score.setScore(result + "");
			score.setExamineBatch(new ExamineBatch(examineBatchId));
			scoreDao.save(score);
		}
		for (ExamineHis his : examineHis) {
			his.setScore(score);
			his.setCreateTime(TimeHelper.getCurrentTime());
			examineHisDao.save(his);
		}

	}

	@Override
	public List<Score> getList(User sysUser) {
		Map<String, Object> map = new HashMap<String, Object>();
		String hql = "from Score a where 1=1";
		if ("1".equals(sysUser.getUserType())) {
			hql += " and a.user.userId=:userId";
			map.put("userId", sysUser.getUserId());
		}
		return scoreDao.find(hql, map);
	}

	@Override
	public Score getByKey(String id) {
		return scoreDao.getByKey(id);
	}

}
